package com.c.service.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.pool.DruidDataSource;
import com.c.result.SingleResult;
import com.c.util.JsonUtils;

import cn.hutool.core.date.DateTime;
import cn.hutool.db.Entity;
import cn.hutool.db.SqlRunner;
import cn.hutool.json.JSONObject;

@Service
public class SQLRunnerService {

	@Autowired
	private DruidDataSource ds;

	public SingleResult<String> sqlrunner(String sql) {
		SingleResult<String> result = new SingleResult<String>();
		SqlRunner runner = SqlRunner.create(ds);
		try {
			List<JSONObject> data = new ArrayList<JSONObject>();
			List<Entity> list = runner.query(sql);
			if (list.size() > 0) {
				System.out.println("sql查询获取数据:" + list.size());
				Long token = new Date().getTime();
				// 创建新的表
				String createTableSQL = "";
				if (!sql.contains("temp")) {
					createTableSQL = "CREATE TABLE temp_" + token + "  (  content" + "  VARCHAR(255) )";
					runner.execute(createTableSQL);
				}
				// 往这张表里插入数据
				for (int i = 0; i < list.size(); i++) {
					Entity map = list.get(i);
					Iterator entries = map.entrySet().iterator();
					String row_data = "";
					Map.Entry entry0 = (Map.Entry) entries.next();
					String value0 = String.valueOf(entry0.getValue());
					row_data = value0;
					while (entries.hasNext()) {
						Map.Entry entry = (Map.Entry) entries.next();
						String value = String.valueOf(entry.getValue());
						row_data = row_data + "______" + value;
					}
					JSONObject row_json = new JSONObject();
					row_json.put("content", row_data);
					data.add(row_json);
					Entity row = Entity.create("temp_" + token).set("content", row_data);
					if (!sql.contains("temp")) {
						runner.insert(row);
					}
				}
				Entity log1 = Entity.create("log").set("create_time", new DateTime(new Date()).toString())
						.set("operation", sql).set("operator", "管理员");
				runner.insert(log1);
				if (!sql.contains("temp")) {
					Entity log2 = Entity.create("log").set("create_time", new DateTime(new Date()).toString())
							.set("operation", createTableSQL).set("operator", "创建新的表");
					runner.insert(log2);
				}

				result.setData(JsonUtils.objectToJson(data));
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.setSuccess(false);
		return result;
	}
}
